import { glob } from "glob";
import { basename, dirname, extname, format, join, relative } from "path";
import fs from "node:fs";
import * as esbuild from "esbuild";
import { watch } from "fs";

export function winPath(path: string) {
  const isExtendedLengthPath = /^\\\\\?\\/.test(path);
  if (isExtendedLengthPath) {
    return path;
  }
  return path.replace(/\\/g, "/");
}

const getRoutes = (items: any, pid: any) => {
  let i = 0;
  const flat = (items: any, pid: any) => {
    let list: any = [];
    items.forEach((item: any) => {
      i++;
      const route = {
        path: item?.path,
        element: item?.element,
        id: `${i}`,
        pid: `${pid}`,
      };
      list.push(route);
      if (item?.children?.length) {
        list = list.concat(flat(item?.children, i));
      }
    });
    return list;
  };
  return flat(items, pid);
};

async function saveRoutes(path: string) {
  try {
    const tempFile = join(process.cwd(), "./src/.qps/cache/routes-tempFile.js");
    // if (fs.existsSync(tempFile)) {
    //   fs.unlinkSync(tempFile);
    // }

    esbuild.buildSync({
      entryPoints: [path],
      outfile: tempFile,
    });

    const routes = await import(tempFile);
    console.log(routes)
    const list = getRoutes(routes.default, 0);
    console.log("tempFile", new Date(), list);
    let routeComponents = list
      .map((item: any) => {
        return `${item.id}:React.lazy(() => import('${item?.element}')),`;
      })
      .join("\n");

    const str = `//@ts-nocheck
import React from 'react';
export  function getRoutes() {
  const routes = ${JSON.stringify(list)} as const;
  return {
    routes,
    routeComponents:{ ${routeComponents}},
  };
}
`;
    fs.writeFileSync(
      join(process.cwd(), "./src/.qps/plugin-router/routes.tsx"),
      str
    );
 
    // if (fs.existsSync(tempFile)) {
    //   fs.unlinkSync(tempFile);
    // }
  } catch (err) {
    console.error(err);
  }
}
const isChange=(modules, path)=>{
  return modules.some((module)=>module.file===path);
}
export default function routerPlugin() {
  const path = join(process.cwd(), "./src/routes.ts");
  return {
    name: "qps-plugin-router",
  
    async buildStart() {
      await saveRoutes(path);
    },
  
    async handleHotUpdate({ file, modules, read }) {
       if(file===path){
        console.log(file,modules)
        await saveRoutes(path);
       }

    },
  };
}


// export function esbuildWatchRebuildPlugin(options: {
//   onRebuild: (error: BuildFailure | null, result: BuildResult | null) => void;
// }): Plugin {
//   return {
//     name: 'watch-rebuild-plugin',
//     setup(build) {
//       let count = 0;
//       build.onEnd((result) => {
//         if (count++ === 0) {
//           return;
//         }
//         if (result.errors.length > 0) {
//           options.onRebuild(
//             failureErrorWithLog('Build failed', result.errors, result.warnings),
//             null,
//           );
//           return;
//         }
//         options.onRebuild(null, result);
//       });
//     },
//   };
// }
